from rest_framework.viewsets import ModelViewSet

from celery_tasks.detail.tasks import generate_detail_html
from goods.models import SKUImage
from meiduo_admin.utils.pagination import MeiduoPagination
from meiduo_admin.serializers.images import ImageModelSerializer
from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response


class ImageModelViewSet(ModelViewSet):
    queryset = SKUImage.objects.all().order_by('-id')
    serializer_class = ImageModelSerializer
    pagination_class = MeiduoPagination

    def create(self, request, *args, **kwargs):
        # 接收、
        sku_id = request.data.get('sku')
        image_file = request.data.get('image')
        # 验证
        if not all([sku_id, image_file]):
            raise serializers.ValidationError('数据不全')
        # 处理 ：上传图片
        client = Fdfs_client(settings.FDFS_CLIENT_PATH)
        ret = client.upload_by_buffer(image_file.read())
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        # 获取文件名
        image_name = ret['Remote file_id']
        # 处理：创建对象
        image = SKUImage.objects.create(sku_id=sku_id, image=image_name)
        # 完善 ‘’ None False区别
        sku = image.sku
        if not sku.default_image:
            sku.default_image = image.image
            sku.save()

            generate_detail_html.delay(sku.id)

        # 响应
        serializer = self.get_serializer(image)

        return Response(serializer.data,status=201)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        # 删数据
        instance.delete()
        # 删图片
        client = Fdfs_client(settings.FDFS_CLIENT_PATH)
        client.delete_file(instance.image.name)

        return Response(status=204)

    def update(self, request, *args, **kwargs):
        # 接收
        sku_id = request.data.get('sku')
        image_file = request.data.get('image')
        # 验证
        if not all([sku_id,image_file]):
            raise serializers.ValidationError('数据不全')
        # 处理：查询对象
        instance = self.get_object()

        image_name_old=instance.image.name

        # 处理 ：删除图片
        client = Fdfs_client(settings.FDFS_CLIENT_PATH)
        client.delete_file(instance.image.name)
        ret = client.upload_by_buffer(image_file.read())
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')

        image_name = ret['Remote file_id']
        # image = SKUImage.objects.create(sku_id=sku_id, image=image_name)
        # 处理：修改
        instance.sku_id = sku_id
        instance.image = image_name
        # instance.default_image = image_name
        instance.save()

        sku=instance.sku
        if sku.default_image==image_name_old:
            sku.default_image=image_name
            sku.save()



        generate_detail_html.delay(sku_id)
        # 响应500dd7dd

        serializer = self.get_serializer(instance)
        return Response(serializer.data,status=201)
